package com.dhl.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * Created by 廖师兄
 * 2018-03-18 20:23
 * 服务降解
 */
//服务错溶
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    //这些配置可以写在配置上面

    //超时配置
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//    })
//

//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),                //设置熔断
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),    //请求数达到后才计算
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //休眠时间窗
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),    //错误率
//    })
    //@HystrixCommand(fallbackMethod = "fallback")//自定义错误提示
    @HystrixCommand
    @GetMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam("number") Integer number) {
        if (number % 2 == 0) {
            return "success";
        }

        RestTemplate restTemplate = new RestTemplate();
        String s= restTemplate.postForObject("http://127.0.0.1:8080/product/listForOrder",
                Arrays.asList("157875196366160022"),
                String.class);
        return  s;

//抛异常也可以触发fallback
//		throw new RuntimeException("发送异常了");
    }

    /**
     * fallback方法的参数类型，参数个数，返回值类型必须要与原方法一样，不然报错
     * fallback method wasn't found: fallback([class java.lang.Integer])
     *
     * @param number
     * @return
     */
    private String fallback(Integer number) {
        return "太拥挤了, 请稍后再试~~";
    }

    private String defaultFallback() {
        return "默认提示：太拥挤了, 请稍后再试~~";
    }
}
